package com.seer.auto.dao.impl;

import com.seer.auto.dao.DefaultRowMapper;
import com.seer.auto.dao.TableConfigDao;
import com.seer.auto.entity.Column;
import com.seer.auto.entity.Table;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class TableConfigTemplate implements TableConfigDao {

    @Autowired
    private JdbcTemplate template;

    @Override
    public Map<String, Table> listTables() {
        String sql = "SELECT table_name as name, column_name as columnName, data_type as dataType, extra FROM information_schema.columns WHERE table_schema='autoserver';";
        Map<String, Table> map = new HashMap<>();
        template.query(sql, (rs, c) -> {
            Table t = map.get(rs.getString("name"));
            if (null == t) {
                t = new Table();
                t.setName(rs.getString("name"));
                t.setColumns(new ArrayList<>());
                map.put(t.getName(), t);
            }
            Column cmn = new Column();
            cmn.setName(rs.getString("columnName"));
            cmn.setDataType(rs.getString("dataType"));
            cmn.setExtra(rs.getString("extra"));
            t.getColumns().add(cmn);
            return map;
        });
        return map;
    }

    @Override
    public Table findByTableName(String name) {
        String sql = "SELECT column_name as name, data_type as dataType, extra FROM information_schema.columns WHERE table_schema='autoserver' and table_name = ?;";
        Table t = new Table();
        t.setName(name);
        List<Column> columns = template.query(sql, DefaultRowMapper.getRowMapper(Column.class), name);
        if (columns.isEmpty()) {
            return null;
        }
        t.setColumns(columns);
        return t;
    }
}
